﻿<%@ page contentType="text/html; charset=utf-8" language="java" %>
<script>
function initUserGrid(_url){
	$('#userTable').datagrid({
		title:'用户查询',
		iconCls:'icon-bumen',
		method:'POST',
		width:665,
		height:450,
		nowrap: false,
		striped: true,
		collapsible:false,
		url: _url,
		idField:'id',
		columns:[[
			//{field:'ck',checkbox:true,width:2}, 
			{field:'loginName',title:'登录名',width:120},
			{field:'name',title:'姓名',width:120},
			{field:'orgNameCn',title:'所属公司',width:360},
			{field:'email',title:'Email',width:150},
			{field:'sysroles',title:'系统角色',width:360},
			{field:'sysroleids',hidden:'true'},
			{field:'orgId',title:'orgId',width:100,hidden:'true'},
			{field:'orgCode',hidden:'true'}
		]],
		pagination:true,
		pageSize:10,
		rownumbers:true,
		
		toolbar:'#userToolBar',
		onLoadSuccess:function(){
			$('#userTable').datagrid('clearSelections'); //一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
		}//,onDblClickRow:function(rowIndex, rowData) {updateUserRow(rowData);}
	});
}

//新增
function addUserRow(){
	openWin3('MyPopWindow','人员维护');
	$('#userForm').form('clear');
	$("#showorgname").text("");
	initAllRoles();
}
function setOrgInfo(row){
	if(typeof(row)!=undefined&&row!=null){
		$("#orgCode").val(row.orgCode);
		$("#orgId").val(row.orgId);
		$("#showorgname").text(row.orgNameCn);
		$("#orgNameCn").val(row.orgNameCn);
		$("#company").val(row.orgType);		
	}
}


function addOrgUserRow(){
	openWin3('MyPopWindow','人员维护');
	$('#userForm').form('clear');
	initAllRoles();
	setOrgInfo();	
		
}


//更新
function updateUserRow(data){
	var rows = $('#userTable').datagrid('getSelections');
	//这里有一个jquery easyui datagrid的一个小bug，必须把主键单独列出来，要不然不能多选
	if(rows.length==0){
		$.messager.alert('提示',"选择用户",'info');
		return;
	}
	
	initAllRoles();
	openWin3('MyPopWindow','人员维护');
	$("#userForm").form('load', rows[0]);	
	setOrgInfo(rows[0]);
}

function restPass(){
		var rows = $('#userTable').datagrid('getSelections');
		if(rows.length==0){
			$.messager.alert('提示',"请选择用户",'info');
			return;
		}
	$.messager.confirm('提示','确认重置密码?',function(result){
        if (result){
				$.postJSON(
		             '${ctx}/Mng/user/resetUserPwd/'+rows[0].id,
					 $("#userForm").serializeObject(),
		             function(data) {
						 if (data && data.success == "true") {
							 $.messager.alert('提示','密码已重置成功：新密码[ 123456 ]','info');
						  } else {
							 $.messager.alert("处理失败",data.infoMsg,'error');
						  }
		           	}
	               );
				}
        });
}

function addOrUpdateUser(){
	var r = $('#userForm').form('validate');
	if(!r) {
		return false;
	}
	if($("#orgCode").val()==""){
		//return;
	}
	progressing();
	$.postJSON(
		'${ctx}/Mng/user/addOrUpdateUser',
		$("#userForm").serializeObject(),
		function(data) {
		progressed();
			if (data && data.success == "true") {
				$('#MyPopWindow').window('close');
				$('#userTable').datagrid('reload');  
				showInfo();
			} else {
				if(data.check_name =="false"){
				 	showInfoCenter('登录名重复','error');
				}else{
				 	$.messager.alert("处理失败",data.infoMsg,'error');
				}
					
			}
		}
	);
}

	
//删除
function deleteUserRow(){
		var rows = $('#userTable').datagrid('getSelections');
		//这里有一个jquery easyui datagrid的一个小bug，必须把主键单独列出来，要不然不能多选
		if(rows.length==0){
			$.messager.alert('提示',"选择用户",'info');
			return;
		}
	
		$.messager.confirm('提示','确认删除',function(result){
        if (result){
        	var ps = "";
        	$.each(rows,function(i,n){
        		if(i==0) 
        			ps += "/"+n.id;
        		else
        			ps += ","+n.id;
        	});
        	$.ajax({
				type: 'get',
				url : '${ctx}/Mng/user/delete' + ps,
				beforeSend:function(){
					$("body").mask("正在处理中...");
        		},
			    success: function(data) {
        			$("body").unmask();
        			if (data && data.success == "true") {
                    	$('#userTable').datagrid('reload');  
            		} else {
            			if(data.check_name =="false")
            				{
            				 showInfo('登录失败','error');
            				}
            			else
            				{
            				 showInfo('稍后重试'+data.check_name);
            				}
            			    
            		}
			    }
			});
        	
        }
    });
}
//表格查询
function searchUser(){
	var params = $('#userTable').datagrid('options').queryParams; //先取得 datagrid 的查询参数
	var fields =$('#queryForm').serializeArray(); //自动序列化表单元素为JSON对象
	
	$.each( fields, function(i, field){
		params[field.name] = field.value; //设置查询参数
	}); 
	
	$('#userTable').datagrid('reload'); //设置好查询参数 reload 一下就可以了
}
//清空查询条件
function clearForm(){
	$('#queryForm').form('clear');
	searchUser();
}

function checkInArray(str,arr){
   str +='';
   var ar = arr.split(',');
   var f = $.inArray(str, ar); 
   if(f==-1)
   {
	  return false;   
   }
   else
   {
	  return true;   
   }
}
	
function checkUserRoles()
{
	var rows = $('#roleTable').datagrid('getRows');
			var opts = $('#roleids').val();
		   $.each( rows, function(i, field){
					 if(checkInArray(field.id,opts))
					 {
						 $('#roleTable').datagrid('checkRow', i);
					 }
			   }); 

}


function initAllRoles()
{
	$('#roleTable').datagrid({
		title:'用户角色授权',
		iconCls:'icon-bumen',
		method:'POST',
		width:200,
		nowrap: false,
		striped: true,
		collapsible:false, 
		url: '${ctx}/Mng/role/alllist',
		idField:'id',
		onCheck:function (rowIndex,rowData){
			    updateUserRoles();       
			},
		onUncheck:function (rowIndex,rowData){
			    updateUserRoles();  
			},
		onSelectAll:function (rows){
			    updateAllRoles(rows);       
			},
		columns:[[
			{field:'ck',checkbox:true,width:2}, 
			{field:'roleName',title:'角色名称',width:120}
		]],
		rownumbers:true,
		onLoadSuccess:function(){
			$('#roleTable').datagrid('clearSelections'); //一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
			checkUserRoles();
		}
	});
}

function updateUserRoles()
{
	
	 var str='';  
     var s='';
     var rows = $('#roleTable').datagrid('getSelections');

			    for(i=0;i<rows.length;i++)
			    {
                          if(i==0)
                                 {
                                     str += rows[i].roleName;
                                     s += rows[i].id;
                                  }
                                  else
                                  {
                                     str += ","+rows[i].roleName;
                                     s +=  ","+rows[i].id;
                                   }
			    }
 
                                $('#rolecbo').val(str);
                                $('#roleids').val(s);
}


function updateAllRoles(rows)
{
					        
	 var str='';  
     var s='';
			    for(i=0;i<rows.length;i++)
			    {
                          if(i==0)
                                 {
                                     str += rows[i].roleName;
                                     s += rows[i].id;
                                  }
                                  else
                                  {
                                     str += ","+rows[i].roleName;
                                     s +=  ","+rows[i].id;
                                   }
			    }
 
                                $('#rolecbo').val(str);
                                $('#roleids').val(s);

}


//显示角色列表
function showroles(){
	//var v = $('#rolecbo').val();
	  var arr = $('#roleids').val();
	  $('#roleDiv').css("display","block");
	  $.ajax({
				type: 'get',
				url : '${ctx}/Mng/role/allRoles',
			    success: function(data) {
			    var jsonlist = data.rolelist;
			    var shtml="<ul style='list-style-type:none'>";
			    $.each(jsonlist,function(i, n){
			    	    if(checkInArray(n.id,arr))
			    	    {
			    	    	
	                    	shtml += "<li><input type='checkbox' name='lang' checked='checked' value='"+n.id+"'><span>"+n.roleName+"</span></li>"
	                    }
	                    else
	                    {
	                    	shtml += "<li><input type='checkbox' name='lang' value='"+n.id+"'><span>"+n.roleName+"</span></li>"
	                    }
                    });
                shtml +="</ul>";
                shtml +="<br><input type='button' id='divClose' value='确定' onclick='choserole();'/>";
                $('#roleDiv').html(shtml);
					 
				}

			});
	  
   
}

function checkInArray(str,arr){
	   str +='';
	   var ar = arr.split(',');
	   var f = $.inArray(str, ar); 
	   if(f==-1)
	   {
		  return false;   
	   }
	   else
	   {
		  return true;   
	   }
}

function choserole(){
		var str='';  
		var s='';
		 $('input[name="lang"]:checked').each(function(i){    
			 if(i==0)
			 {
				 str += $(this).next('span').html();
				 s += $(this).val();
			  }
			  else
			  {
				 str += ","+$(this).next('span').html();
				 s +=  ","+$(this).val();
			   }

		  });   
		$('#rolecbo').val(str);
		$('#roleids').val(s);
	    $('#roleDiv').css("display","none");
}


function setUpOrgInfo(){
	//$('#orgSelectWin').window('open');
	openWin3("orgSelectWin","机构选取 >> 双击选取");
}
function setSelOrgNode(node){
	if(node){
		$("#orgId").val(node.id);
		$("#orgCode").val(node.orgCode);
		$("#orgNameCn").val(node.text);
		$('#orgSelectWin').window('close');
	}else{
		showInfoCenter("未选取机构！");
	}
}

$(document).ready(function(){
	 
});
function init(){
	

}
</script>

<div id="MyPopWindow" class="easyui-window" data-options="closed:true,modal:true,collapsible:false,minimizable:false,maximizable:false,draggable:true,onOpen:function(){}" >
  <table class="listTable" align="center" width="100%" height="100%">
    <tr>
		<th colspan="2"><span class="alertInfo">提示：新用户，或密码重置用户，密码统一为 123456</span></th>
	</tr>
	<tr>
      <td width="40%" valign="top">
	  <form id="userForm" method="post">
	  <input type="hidden" id="" name="id" value=""/>
	  <input type="hidden" id="roleids" name="sysroleids" value=""/>
	  <input type="hidden"  name="sysroles" id="rolecbo" value=""/>
		<input type="hidden" name="orgCode" id="orgCode">
		<input type="hidden" name="orgId" id="orgId">
		<input type="hidden" name="company" id="company">

          <table width="100%">
            <tr height="30" >
              <td align="left" nowrap="nowrap">登陆名：</td>
              <td align="left"><input class="easyui-validatebox" type="text" name="loginName" maxlength="25" required="true">
                </input></td>
            </tr>
            <tr height="30">
              <td align="left">姓    名：</td>
              <td align="left"><input class="easyui-validatebox" type="text" name="name" maxlength="25" required="true">
                </input></td>
            </tr>
            <tr height="30" >
              <td align="left">Email：</td>
              <td align="left"><input class="easyui-validatebox" type="text" name="email" maxlength="40" validType="email">
                </input></td>
            </tr>
	 <shiro:hasPermission name="____AgentAdmin">
            <tr>
              <td>所在机构</td>
              <td>
                <span id="showorgname"></span>
				<!-- only for Admin-->
				<div id="selectOrgArea">
				<input type="text" class="easyui-validatebox" name="orgNameCn" id="orgNameCn" readonly="true" onClick="setUpOrgInfo()">
                <a class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" href="javascript:void(0);" onClick="setUpOrgInfo()">选取</a>
				</div>
				</td>
            </tr>
	 </shiro:hasPermission>
            <tr height="30" > 
              <td colspan="2" align="center"><a href="javascript:void(0);" id="btn-back" onclick="$('#MyPopWindow').window('close');" class="easyui-linkbutton" iconcls="icon-back">返回</a> <a href="javascript:void(0);" id="btn-add" onclick="addOrUpdateUser();" class="easyui-linkbutton" iconcls="icon-save">保存</a> </td>
            </tr>
          </table>
        </form>
		</td>
      	<td>
			<table id="roleTable" title="Basic DataGrid"  data-options="fit:true">
              </table>
		</td>
    </tr>
  </table>
</div>
<div id="orgSelectWin" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-edit',title:'机构'" style="width:560px;height:460px;padding:10px;">
  <ul id="orgTreeObject" class="easyui-tree" data-options="url:'${ctx}/Mng/org/treeGridData',animate:true,dnd:true,onDblClick:function(node){setSelOrgNode(node);}">
  </ul>
</div>